using UnityEngine;
using System;
using TEngine;
using System.Security.Cryptography.X509Certificates;
using DG.Tweening;
using UnityEngine.UI;

namespace GameLogic
{

    /// <summary>
    /// 单元格控制基类
    /// </summary>

    public abstract class CellCtrl : MonoBehaviour
    {
        #region 组件
        protected RectTransform _rectParent;
        protected RectTransform _rectSelf;
        #endregion

        #region 属性字段
        protected Vector2Int _pos;
        public Vector2Int CurrentPos { get; internal set; }
        #endregion 

        #region 生命周期
        #endregion

        #region 逻辑
        public virtual void InitCell(Vector2Int pos, RectTransform rectParent)
        {
            _rectSelf = gameObject.GetOrAddComponent<RectTransform>();
            _pos = pos;
            CurrentPos = pos;
            _rectParent = rectParent;
            // 设置锚点和轴心为左下角
            _rectSelf.anchorMin = new Vector2(0, 0);
            _rectSelf.anchorMax = new Vector2(0, 0);
            _rectSelf.pivot = new Vector2(0, 0);
        }

        /// <summary>
        /// 设置单元格位置
        /// </summary>
        /// <param name="pos">网格坐标</param>
        /// <param name="isAmin">是否使用动画（暂未实现）</param>
        /// <summary>
        /// 设置单元格位置（基于网格坐标）
        /// </summary>
        /// <param name="pos">网格坐标(X列,Y行)</param>
        /// <param name="isAmin">是否使用动画移动</param>
        public virtual void SetPos(Vector2Int pos, bool isAmin = false)
        {
            if (_rectParent == null)
            {
                Log.Error("Parent rect transform is not initialized");
                return;
            }

            _pos = pos;

            if (!isAmin)
            {
                // 根据父容器实际尺寸和单元格尺寸计算位置
                var cellWidth = _rectSelf.sizeDelta.x;
                var cellHeight = _rectSelf.sizeDelta.y;
                
                // 计算最终位置（左下角原点）
                var targetPos = new Vector2(
                    _pos.x * cellWidth,
                    _pos.y * cellHeight
                );

                // 添加边界检查
                if (targetPos.x + cellWidth > _rectParent.rect.width ||
                    targetPos.y + cellHeight > _rectParent.rect.height)
                {
                    Log.Warning($"Cell at {pos} exceeds parent container bounds");
                }

                _rectSelf.anchoredPosition = targetPos;
            }
            else
            {
                // 动画移动实现占位
                StartMoveAnimation(pos);
            }
        }

        private DG.Tweening.Tween _currentTween;
        
        /// <summary>
        /// 判断当前单元格是否有动画正在播放
        /// </summary>
        public bool IsAnimating()
        {
            return _currentTween != null && _currentTween.IsActive();
        }

        /// <summary>
        /// 启动移动动画
        /// </summary>
        private void StartMoveAnimation(Vector2Int targetPos)
        {
            // 计算目标位置
            var targetPosition = new Vector2(
                targetPos.x * _rectSelf.sizeDelta.x,
                targetPos.y * _rectSelf.sizeDelta.y
            );

            // 如果已经有正在进行的动画，先停止
            _currentTween?.Kill();

            // 使用DOTween实现平滑动画
            _currentTween = _rectSelf.DOAnchorPos(targetPosition, 0.3f)
                .SetEase(DG.Tweening.Ease.OutQuad)
                .OnStart(() => {
                    // 动画开始时确保激活状态
                    if (!gameObject.activeSelf) gameObject.SetActive(true);
                })
                .OnUpdate(() => {
                    // 更新逻辑位置（如果需要实时跟踪）
                    _pos = targetPos;
                })
                .OnComplete(() => {
                    // 确保最终位置准确
                    _rectSelf.anchoredPosition = targetPosition;
                    _currentTween = null;
                })
                .OnKill(() => {
                    // 立即跳到最终位置
                    _rectSelf.anchoredPosition = targetPosition;
                    _currentTween = null;
                });
        }

        public virtual void SetSize(float cellWidth, float cellHeight)
        {
            _rectSelf.sizeDelta = new Vector2(cellWidth, cellHeight);
        }
        #endregion
    }
}
